//
//  EditPassengersController.swift
//  AirTravel
//
//  Created by apple on 2021/8/13.
//

import UIKit
import Moya
import SwiftyJSON

protocol EditPassengersDelegate:NSObjectProtocol {
    func editPassengersClick(number:Int)
    func addPassengersClick(type:Int)
}

class EditPassengersController: UIViewController {

    @IBOutlet weak var prefixBtn: UIButton!
    @IBOutlet weak var submitBt: UIButton!
    @IBOutlet weak var phoneTf: UITextField!
    @IBOutlet weak var idCardTf: UITextField!
    @IBOutlet weak var idTypeTf: UITextField!
    @IBOutlet weak var nameTf: UITextField!
    var idTypeView:IdTypePickView!
    var idTypeNum = 0
    var countryNum = ""
    var identity_type = "1"
    var number = 0
    
    var is_editor = false
    
    
    var tag = 0
    var dataDic : Dictionary<String,Any>?
    weak var delegate: EditPassengersDelegate?
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
        self.navigationController?.navigationBar.tintColor = UIColor.black
        self.navigationController?.navigationBar.titleTextAttributes = [
            NSAttributedString.Key.foregroundColor : UIColor.black]
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationController?.navigationBar.titleTextAttributes = [
            NSAttributedString.Key.foregroundColor : UIColor.white]
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if is_editor {
            
            if(tag == 1){
                self.title = "编辑入住人"
            }else{
                self.title = "编辑乘客"
            }
            
            if let dic = self.dataDic {
                let doument_type = Int("\(dic["doument_type"] ?? "1")")
                self.idTypeNum = doument_type ?? 1
                switch self.idTypeNum {
                case 1:
                    self.idTypeTf.text = "身份证"
                case 2:
                    self.idTypeTf.text = "护照"
                case 3:
                    self.idTypeTf.text = "军人证"
                case 4:
                    self.idTypeTf.text = "回乡证"
                case 5:
                    self.idTypeTf.text = "台胞证"
                case 6:
                    self.idTypeTf.text = "外国人永久居留证"
                case 99:
                    self.idTypeTf.text = "其他"
                default:
                    break
                }
                let identity_type = "\(dic["identity_type"] ?? "")"
                self.identity_type = identity_type
                self.nameTf.text = "\(dic["name"] ?? "")"
                self.idCardTf.text = "\(dic["idcard"] ?? "")"
                self.phoneTf.text = "\(dic["mobile"] ?? "")"
            }
            
            setupNavigationItems()
        }else{
            self.title = "新增乘客"
        }
        
        self.submitBt.layer.cornerRadius = 6
        self.submitBt.layer.masksToBounds = true
        let gradientLayer0 = CAGradientLayer()
        gradientLayer0.cornerRadius = 6
        gradientLayer0.frame = self.submitBt.bounds
        gradientLayer0.colors = [
            UIColor(red: 101.0 / 255.0, green: 160.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0).cgColor,
            UIColor(red: 48.0 / 255.0, green: 124.0 / 255.0, blue: 248.0 / 255.0, alpha: 1.0).cgColor]
        gradientLayer0.locations = [0, 1]
        gradientLayer0.startPoint = CGPoint(x: 0, y: 1)
        gradientLayer0.endPoint = CGPoint(x: 1, y: 1)
        self.submitBt.layer.addSublayer(gradientLayer0)
        self.idTypeTf.delegate = self
    }
    
    private func setupNavigationItems() {
        let customButton1 = UIButton.init(type: .custom)
        customButton1.frame = CGRect.init(x: 0, y: 0, width: 45, height: 45)
        customButton1.setTitle("删除", for: .normal)
        customButton1.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        customButton1.setTitleColor(UIColor.black, for: .normal)
        customButton1.addTarget(self, action: #selector(scanCode), for: .touchUpInside)
        let leftButtonItem = UIBarButtonItem.init(customView: customButton1)
        self.navigationItem.rightBarButtonItem = leftButtonItem
    }
    //删除
    @objc func scanCode() {
        cancelableRequest = NetWorkRequest(API1.delUserIdCard(parameters: ["id":"\(self.dataDic?["id"] ?? "")"]), completion: {[weak self] (responseString) -> (Void) in
            YProgressHUD.showToast("删除成功")
            self?.delegate?.editPassengersClick(number: self?.number ?? 0)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self?.navigationController?.popViewController(animated: true)
            }
            
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    //选电话国际区号
    @IBAction func prefix(_ sender: UIButton) {
        let vc = CountryController()
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //提交
    @IBAction func submit(_ sender: UIButton) {
        if self.nameTf.text?.isEmpty == true{
            YProgressHUD.showToast("姓名不能为空")
            return
        }
        if self.idTypeNum == 0{
            YProgressHUD.showToast("证件类型不能为空")
            return
        }
        if self.idCardTf.text?.isEmpty == true{
            YProgressHUD.showToast("证件号码不能为空")
            return
        }
        if self.phoneTf.text?.isEmpty == true{
            YProgressHUD.showToast("电话号码不能为空")
            return
        }
        if is_editor {
            updateUserIdCard()
        }else{
            gitIdCardList()
        }
    }
    
    //获取用户身份证信息
    func gitIdCardList() {
        
        cancelableRequest = NetWorkRequest(API1.addUserIdCard(parameters: ["doument_type":self.idTypeNum,"mobile":self.phoneTf.text ?? "","name":self.nameTf.text ?? "","idcard":self.idCardTf.text ?? "","identity_type":self.identity_type]), completion: {[weak self] (responseString) -> (Void) in
            YProgressHUD.showToast("新增成功")
            self?.delegate?.addPassengersClick(type: self?.number ?? 0)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self?.navigationController?.popViewController(animated: true)
            }
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
    //身份证修改
    func updateUserIdCard() {
        
        cancelableRequest = NetWorkRequest(API1.updateUserIdCard(parameters: ["doument_type":self.idTypeNum,"mobile":self.phoneTf.text ?? "","name":self.nameTf.text ?? "","idcard":self.idCardTf.text ?? "","identity_type":self.identity_type,"id":"\(self.dataDic?["id"] ?? "")"]), completion: {[weak self] (responseString) -> (Void) in
            YProgressHUD.showToast("修改成功")
            self?.navigationController?.popViewController(animated: true)
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
}

extension EditPassengersController:UITextFieldDelegate{
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
        
        if textField.tag == 1 {
            self.view.endEditing(true)
            if idTypeView == nil {
                idTypeView=IdTypePickView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
                idTypeView.myidType={[weak self](turple) in
                                    
                    self?.idTypeNum=turple.0
                    self?.idTypeTf.text = turple.1
                }
            }
            
            self.view.addSubview(idTypeView)
            return false
        }
        return true
    }
}

extension EditPassengersController:countryNumChooseDelegate{
    func countryNumChoosed(_ countryNum: String) {
        self.countryNum = countryNum
        self.prefixBtn.setTitle("+\(countryNum)", for: .normal)
    }
}
